package com.centit.framework.web.demo.config;

import com.alibaba.fastjson.JSONObject;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.WebOptUtils;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.security.model.CentitUserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Component
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setContentType("text/html;");
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        // PrintWriter out = resp.getWriter();
        // 得到用户请求的URI
        String request_uri = req.getRequestURI();
        // 得到web应用程序的上下文路径
        String ctxPath = req.getContextPath();
        // 去除上下文路径，得到剩余部分的路径
        String uri = request_uri.substring(ctxPath.length());
        // 判断用户访问的是否是登录页面
        CentitUserDetails userDetails=WebOptUtils.getLoginUser(req);
        String url = "http://" + req.getServerName()+":" + req.getServerPort()  + req.getContextPath()  + req.getServletPath() ;

        if (userDetails!=null) {
            chain.doFilter(request, response);
            return;
        } else {
            String requestType = req.getHeader("X-Requested-With");
           //判断是否是ajax请求
            if(requestType!=null && "XMLHttpRequest".equals(requestType)){
                JsonResultUtils.writeErrorMessageJson(401,"平台登录信息失效，请重新登录,2s后自动跳转",resp);
            }

        }
    }

    @Override
    public void destroy() {

    }
}
